<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>子传父</title>
</head>
<body>
<!--
  单独的事件中心管理组件间通信
  let eventHub = new Vue()
  监听事件和销毁事件
  eventHub.$on('add-todo', addTodo)
  eventHub.$off('add-todo')
  触发事件
  eventHub.$emit('add-todo', id)
-->

<div id="app">
  <div>父组件</div>
  <div>
    <button @click="handle">销毁事件</button>
  </div>
  <hr>
  <tom></tom>
  <jerry></jerry>
</div>

<script src="../lib/vue.js"></script>
<script>
  let hub = new Vue();


  Vue.component('tom', {
    template: `
      <div>
        <div>TOM: {{num}}</div>
        <div>
          <button @click="handle">点击</button>
        </div>
      </div>
    `,
    data() {
      return {
        num: 0
      }
    },
    methods: {
      handle() {
        hub.$emit('jerry-event', 2)
      }
    },
    mounted() {
      hub.$on('tom-event', (val) => {
        this.num += val;
      })
    }
  })

  Vue.component('jerry', {
    template: `
      <div>
        <div>Jerry: {{num}}</div>
        <div>
          <button @click="handle">点击</button>
        </div>
      </div>
    `,
    data() {
      return {
        num: 0
      }
    },
    methods: {
      handle() {
        hub.$emit('tom-event', 1)
      }
    },
    mounted() {
      // 监听
      hub.$on('jerry-event', (val) => {
        this.num += val;
      })
    }
  })

  let vm = new Vue({
    el: '#app',
    methods: {
      handle() {
        hub.$off('tom-event')
        hub.$off('jerry-event')
      }
    }
  })
</script>

</body>
</html>